/**
 * 
 */
package com.geekteam.masterenglish.ui.fragment;

import java.io.File;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.geekteam.masterenglish.R;
import com.geekteam.masterenglish.entity.DataRequest;
import com.geekteam.masterenglish.provider.EEContract.Lession;
import com.geekteam.masterenglish.service.EEService;
import com.geekteam.masterenglish.utils.Constants;
import com.geekteam.masterenglish.utils.Constants.BundleKey;
import com.geekteam.masterenglish.utils.Constants.TypeRequest;
import com.geekteam.masterenglish.utils.NetworkUtils;
import com.geekteam.masterenglish.utils.Utils;

/**
 * @author MTROL
 *
 */
public class DetailLessionFragment extends BaseFragment implements LoaderCallbacks<Cursor>{

	private static final String TAG = "DetailLessionFragment";
	private TextView mTitleTextView;
	private TextView mContentTextView;
	private String mLessionId;
	private boolean isVisible;
	private boolean isPlaying;
	private String mTittle;
	private String mContent;
	private String mUrl;
	private String mUrlDownload;
	private String mId;
	private String mAlbumName;
	
	public DetailLessionFragment() {
	}
	
	public DetailLessionFragment(String lessionId){
		mLessionId = lessionId;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(savedInstanceState!=null){
			restoreInstanceState(savedInstanceState);
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
	private void restoreInstanceState(Bundle savedInstanceState){
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_detail_lession, container, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mTitleTextView = (TextView) getView().findViewById(R.id.title);
		mContentTextView = (TextView) getView().findViewById(R.id.content);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		getLoaderManager().initLoader(1, null, this);
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		CursorLoader loader = null;
		loader = new CursorLoader(getActivity(), Lession.buildLessionId(mLessionId), LessionQuerry.PROJECT, null, null, null);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if(cursor.moveToFirst()){
			mTittle = cursor.getString(cursor.getColumnIndex(Lession.TITLE));
			mContent = cursor.getString(cursor.getColumnIndex(Lession.TEXT));
			mAlbumName = cursor.getString(cursor.getColumnIndex(Lession.ALBUM_NAME));
			mId = cursor.getString(cursor.getColumnIndex(Lession.ID));
			mUrl = cursor.getString(cursor.getColumnIndex(Lession.LINK_128));
			mUrlDownload = cursor.getString(cursor.getColumnIndex(Lession.LINKDOWN_128));
			
			mTitleTextView.setText(mTittle);
			mContentTextView.setText(mContent);
			mActivity.getSupportActionBar().setTitle(mAlbumName);
			mActivity.onShowMenuDownload();
			
			long lastUpdate = cursor.getLong(cursor.getColumnIndex(Lession.UPDATED));
			
			//check update for this lession
			if(Utils.isUpdate(lastUpdate)){
				DataRequest entity = new DataRequest();
				entity.id = mId;
				entity.type = Constants.TYPE_SONG;
				
				Intent intent = new Intent();
				intent.putExtra(BundleKey.TYPE_REQUEST, TypeRequest.GET_DETAIL_LESSION);
				intent.putExtra(BundleKey.DATA_REQUEST, entity);
				intent.setClass(getActivity(), EEService.class);
				getActivity().startService(intent);
			}else{
				playMusic();
			}
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		
	}
	
	public boolean isFragmentUIActive() {
	    return isAdded() && !isDetached() && !isRemoving();
	}
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		isVisible = isVisibleToUser;
		if(isVisibleToUser){
			playMusic();
		}else{
			isPlaying = false;
		}
	}
	
	private void playMusic(){
		if(mUrl==null || mTittle == null){
			return;
		}
		
		if(isVisible && !isPlaying){
//			mActivity.playMusic(mUrl, mTittle);
			
			Log.e(TAG, "prepare playmusic");
			String encodeTitle = Utils.hmacMD5(mTittle, NetworkUtils.PRIVATE_KEY, "HMACMD5");
			Log.e(TAG, "file name: "+encodeTitle);
			File file = new File(getActivity().getExternalFilesDir(getString(R.string.folder_cache)), encodeTitle);
			if(file.exists()){
				//Play Lession from file
				Log.e(TAG, file.getAbsolutePath());
				mActivity.playMusic(file.getAbsolutePath(), mTittle, mAlbumName, mUrlDownload);
			}else{
				mActivity.playMusic(mUrl, mTittle, mAlbumName, mUrlDownload);
				//Download file here
				Log.e(TAG, "start download file");
				Intent intent = new Intent(getActivity(), EEService.class);
				intent.putExtra(BundleKey.URL, mUrlDownload);
				intent.putExtra(BundleKey.TITLE, encodeTitle);
				intent.putExtra(BundleKey.TYPE_REQUEST, TypeRequest.CACHE);
				mActivity.startService(intent);
			}
			
			isPlaying = true;
		}
	}
	
	private interface LessionQuerry{
		String[] PROJECT = {
				Lession._ID,
				Lession.ID,
				Lession.TITLE,
				Lession.COVER,
				Lession.TOTAL_LISTEN,
				Lession.ALBUM_ID,
				Lession.DESCRIPTION,
				Lession.TEXT,
				Lession.LINK_128,
				Lession.LINK_320,
				Lession.LINKDOWN_128,
				Lession.LINKDOWN_320,
				Lession.ALBUM_NAME,
				Lession.UPDATED
		};
	}
}
